from .IDInterface import DInterface
from .IRInterface import RInterface
from adapt.exception import UnpackException

class IRecipe(RInterface, DInterface):
    def __init__(self):
        self.__provides = []
        self.__requres = []
        
    def provides(self, capability):
        self.__provides.append(capability)
        
    def requires(self, capability):
        self.__requres.append(capability)
        

class IRecipeSrc(IRecipe):
    def deploy(self):
        self.download()
        self.unpack()
        self.build()
        self.test()
        self.install()
        
    def download(self):
        import urllib
        path = urllib.parse.urlparse(self.dwnl_uri).path
        self.dwnl_filename = path.split('/')[-1]
        url_obj = urllib.request.urlopen(self.dwnl_uri)
        with open(self.dwnl_filename, 'wb') as f:
            f.write(url_obj.read())
            
    def unpack(self):
        unpacked = None
        method = None
        if 'tar' in self.dwnl_filename:
            method = 'tar'
            import tarfile
            # untar and unpack (bz and gz only, let's say it is enough for now)
            unpacked = tarfile.open(self.dwnl_filename, 'r:*')
        # todo: add here other unpacking mechanisms
        if unpacked:
            if method == 'tar':
                unpacked.extractall()
            else:
                raise UnpackException("Unpacked method not implemented")
        else:
            raise UnpackException("Unpacked method not implemented")
        
            